import { Request, Response, NextFunction, urlencoded, json, static as staticHandler } from 'express'
import express from 'express'
import routes from "./routes/index.js"
import config from "./config/default.js"
import cookieParser from 'cookie-parser'

let app = express();

app.use(cookieParser("1234abcdefg"));
app.all('*', (req: Request, res: Response, next: NextFunction) => {
  const { origin, Origin, referer, Referer } = req.headers;
  // origin || Origin || referer || Referer || 
  const allowOrigin = origin || Origin || referer || Referer || '*';
  res.header("Access-Control-Allow-Origin", allowOrigin);
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  res.header("Content-Type", "application/json; charset=utf-8");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true"); //可以带cookies
  res.header("X-Powered-By", 'Express');
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});
app.use(urlencoded({ extended: true }));
app.use(json());
routes(app);

app.use(staticHandler("./public"));
app.listen(config.port);